// 引入七牛云JavaScript SDK
const qiniu = require('qiniu');
const fs = require('fs');
const https = require('https');
const path = require('path');
// 设置七牛云账号的AccessKey和SecretKey

var accessKey = 'mGyop7FzyekB5l4KokIjx1zHRV6iIgYqay9RoIBK';
var secretKey = 'oU7BzeY6Ubi8imTeKGC-tR-oDU5zcvWoRk3-iRZD';

// 设置上传使用的Bucket
const bucket = 'buer3301';
// 初始化七牛云上传配置
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
const options = {
	scope: bucket,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

const config = new qiniu.conf.Config();


exports.main = async (event, context) => {
	try {
		let imageUrlOrPath = event.imageUrlOrPath; // 图片的URL或本地路径，由调用方传递
		const tempDir = 'userTem'
		// 判断是网络图片还是本地路径图片
		if (imageUrlOrPath.startsWith('http://') || imageUrlOrPath.startsWith('https://')) {
			// 处理网络图片
			const tempFilePath = path.join(tempDir, `temp_${Date.now()}.jpg`);
			await downloadImage(imageUrlOrPath, tempFilePath);
			imageUrlOrPath = tempFilePath;
		}

		// 使用七牛云 SDK 上传图片
		const formUploader = new qiniu.form_up.FormUploader(config);
		const putExtra = new qiniu.form_up.PutExtra();

		// 图片的key（即上传后的文件名，可以自定义）
		const key = `${Date.now()}-${Math.random().toString(36).substring(2)}.jpg`;

		// 执行上传操作
		await new Promise((resolve, reject) => {
			formUploader.putFile(uploadToken, key, imageUrlOrPath, putExtra, (respErr, respBody,
				respInfo) => {
				if (respErr) reject(respErr);
				if (respInfo.statusCode === 200) {
					resolve(respBody);
				} else {
					reject(new Error(`Upload failed with status code ${respInfo.statusCode}`));
				}
			});
		});

		// 如果是网络图片，删除临时文件
		if (imageUrlOrPath.startsWith(path.join(tempDir))) {
			fs.unlinkSync(imageUrlOrPath);
		}

		console.log('Image uploaded successfully');
		return {
			success: true,
			imageUrl: `http://scc87ntbr.hn-bkt.clouddn.com/${key}`
		};
	} catch (error) {
		console.error('Error uploading image:', error);
		return {
			success: false,
			error: error.message
		};
	}
};

// 下载网络图片到本地临时文件的辅助函数
async function downloadImage(url, dest) {
	return new Promise((resolve, reject) => {
		const file = fs.createWriteStream(dest);
		const httpOrHttps = url.startsWith('https') ? require('https') : require('http');
		httpOrHttps.get(url, (response) => {
			response.pipe(file);
			file.on('finish', () => {
				file.close(resolve);
			});
		}).on('error', (err) => {
			fs.unlink(dest, () => {}); // 删除临时文件
			reject(err);
		});
	});
}